package io.gitee.yth.design.pattern.test.core.pattern.behavioral.command;

import java.util.ArrayDeque;
import java.util.Arrays;

/**
 * @author yth
 * @since 2023-04-28-23:15
 */
public class RemoteControl {

    private static final Command NO_COMMAND = new NoCommand();

    private final int commandNum;
    private final Command[] onCommands;
    private final Command[] offCommands;
    private final ArrayDeque<Command> lastCommands;    // 仅支持一次撤销操作

    public RemoteControl(int commandNum) {
        this.commandNum = commandNum;
        this.onCommands = new Command[commandNum];
        this.offCommands = new Command[commandNum];
        Arrays.fill(onCommands, NO_COMMAND);
        Arrays.fill(offCommands, NO_COMMAND);
        this.lastCommands = new ArrayDeque<>();
    }

    public void setCommand(int i, Command onCommand, Command offCommand) {
        if (i < 0 || i >= commandNum || onCommand == null || offCommand == null) {
            throw new IllegalArgumentException();
        }
        onCommands[i] = onCommand;
        offCommands[i] = offCommand;
    }

    public void invokeOnCommand(int i) {
        if (i < 0 || i >= commandNum) {
            throw new IllegalArgumentException();
        }
        onCommands[i].execute();
        lastCommands.push(onCommands[i]);
    }

    public void invokeOffCommand(int i) {
        if (i < 0 || i >= commandNum) {
            throw new IllegalArgumentException();
        }
        offCommands[i].execute();
        lastCommands.push(offCommands[i]);
    }

    public void undoCommand() {
        if (lastCommands.isEmpty()) return;
        lastCommands.pop().undo();
    }

}
